package org.jeecg.modules.demo.projectgroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.projectgroup.entity.ProjectGroup;
import org.jeecg.modules.demo.projectgroup.service.IProjectGroupService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 项目分组
 * @Author: jeecg-boot
 * @Date: 2021-12-30
 * @Version: V1.0
 */
@Api(tags = "项目分组")
@RestController
@RequestMapping("/projectgroup/projectGroup")
@Slf4j
public class ProjectGroupController extends JeecgController<ProjectGroup, IProjectGroupService> {
    @Autowired
    private IProjectGroupService projectGroupService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IProjectManagementService projectManagementService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "项目分组-分页列表查询")
    @ApiOperation(value = "项目分组-分页列表查询", notes = "项目分组-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ProjectGroup projectGroup,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<ProjectGroup> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("store_id", storeId).orderByAsc("weight");
        QueryGenerator.initQueryWrapper(queryWrapper, projectGroup, req.getParameterMap());
        Page<ProjectGroup> page = new Page<ProjectGroup>(pageNo, pageSize);
        IPage<ProjectGroup> pageList = projectGroupService.page(page, queryWrapper);

        List<ProjectGroup> listMap = pageList.getRecords();
        listMap.forEach(pg -> {
            int count = projectManagementService.count(new QueryWrapper<ProjectManagement>()
                    .eq("group_id", pg.getId())
                    .eq("store_id", storeId));
            pg.setNumberGoods(count);
        });
        listMap.sort((o1, o2) -> {
            if (o1.equals(o2)) {
                return 0;
            } else if (Integer.parseInt(o1.getWeight()) > Integer.parseInt(o2.getWeight())) {
                //o2为前值，o1为后值；这里理解为：后值比前值大，则不交换位置,等价从小到大排序
                //如果这里返回 -1，则为从大到小排序
                return -1;
            } else {
                //后值比前值小，则交换位置
                return 1;
            }
        });
        return Result.OK(pageList);
    }

    /**
     * 根据店铺id查询项目分组列表（未被前端调用）
     */
    @RequestMapping(value = "/getListByStoreId", method = RequestMethod.GET)
    public Result<List<ProjectGroup>> getListByStoreId(@RequestParam(name = "storeId", required = true) String storeId) {
        Result<List<ProjectGroup>> result = new Result<>();
        List<ProjectGroup> list = projectGroupService.getListByStoreId(storeId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 根据店铺id查询项目分组列表
     */
    @GetMapping(value = "/getGroupList")
    public Result<?> getListByStoreId(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<ProjectGroup> list = projectGroupService.getListByStoreId(storeId);

        return Result.OK(list);
    }

    /**
     * 根据groupId查询项目列表
     */
    @GetMapping(value = "/getProjectListByGroup")
    public Result<?> getProjectListByGroup(String groupId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<ProjectManagement> list = projectManagementService.list(new QueryWrapper<ProjectManagement>()
                .eq("group_id", groupId)
                .eq("store_id", storeId));
        return Result.OK(list);
    }

    /**
     * 根据groupId查询上架项目列表
     */
    @GetMapping(value = "/getProjectListByGroupOut")
    public Result<?> getProjectListByGroupOut(String groupId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<ProjectManagement> list = projectManagementService.list(new QueryWrapper<ProjectManagement>()
                .eq("group_id", groupId)
                .eq("store_id", storeId)
                .eq("is_activate", "1"));
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param projectGroup
     * @return
     */
    @AutoLog(value = "项目分组-添加")
    @ApiOperation(value = "项目分组-添加", notes = "项目分组-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ProjectGroup projectGroup, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        projectGroup.setStoreId(storeId);
        // 当前店铺全部项目分组
        List<ProjectGroup> list = projectGroupService.list(new QueryWrapper<ProjectGroup>().eq("store_id", storeId));
        // list中与projectGroup同名的项目分组个数
        long count = list.stream().filter(pg -> pg.getGroupName().equals(projectGroup.getGroupName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名项目分组！");
        }
        if (projectGroup.getGrossRate() == null) {
            projectGroup.setGrossRate(0.00);
        }
        if (projectGroup.getGrossRate() < 0 || projectGroup.getGrossRate() > 100) {
            return Result.error("添加失败，毛利率应在0-100范围内！");
        }
        projectGroupService.save(projectGroup);
        return Result.OK("添加成功！");

    }

    /**
     * 编辑
     *
     * @param projectGroup
     * @return
     */
    @AutoLog(value = "项目分组-编辑")
    @ApiOperation(value = "项目分组-编辑", notes = "项目分组-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> edit(@RequestBody ProjectGroup projectGroup, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        // 当前店铺全部项目分组
        List<ProjectGroup> list = projectGroupService.list(new QueryWrapper<ProjectGroup>()
                .eq("store_id", storeId)
                .ne("id", projectGroup.getId()));
        // list中与projectGroup同名的项目分组个数
        long count = list.stream().filter(pg -> pg.getGroupName().equals(projectGroup.getGroupName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名项目分组！");
        }
        if (projectGroup.getGrossRate() == null) {
            projectGroup.setGrossRate(0.00);
        }
        if (projectGroup.getGrossRate() < 0 || projectGroup.getGrossRate() > 100) {
            return Result.error("编辑失败，毛利率应在0-100范围内！");
        }
        projectGroupService.updateById(projectGroup);
        // 更新项目表中的项目分组名称
        ProjectManagement pm = new ProjectManagement();
        pm.setProjectGroup(projectGroup.getGroupName());
        projectManagementService.update(pm, new QueryWrapper<ProjectManagement>().eq("group_id", projectGroup.getId()));
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目分组-通过id删除")
    @ApiOperation(value = "项目分组-通过id删除", notes = "项目分组-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(@RequestParam("id") String id) {
        projectGroupService.removeById(id);
        // 删除项目分组时，将关联的项目的项目分组属性清空
        ProjectManagement pm = new ProjectManagement();
        pm.setGroupId("");
        pm.setProjectGroup("");
        projectManagementService.update(pm, new QueryWrapper<ProjectManagement>().eq("group_id", id));
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目分组-批量删除")
    @ApiOperation(value = "项目分组-批量删除", notes = "项目分组-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        this.projectGroupService.removeByIds(idList);
        // 删除项目分组时，将关联的项目的项目分组属性清空
        ProjectManagement pm = new ProjectManagement();
        pm.setGroupId("");
        pm.setProjectGroup("");
        projectManagementService.update(pm, new QueryWrapper<ProjectManagement>().in("group_id", idList));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目分组-通过id查询")
    @ApiOperation(value = "项目分组-通过id查询", notes = "项目分组-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ProjectGroup projectGroup = projectGroupService.getById(id);
        if (projectGroup == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(projectGroup);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param projectGroup
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ProjectGroup projectGroup) {
        return super.exportXls(request, projectGroup, ProjectGroup.class, "项目分组");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ProjectGroup.class);
    }

}
